
class SpeechPlayer {
  constructor() {
    this.audio = new Audio();

    // initialValue
    this.textBuffer = '';
    this.played = false;
  }

  playText(text) {
    this.getToken((token, flag) => {
      this.audio.src = `https://tsn.baidu.com/text2audio?tex=${encodeURI(text)}&lan=zh&cuid=123A&ctp=1&tok=${token}`;
      if (this.audio && this.audio.play) {
        this.audio.play().then((res) => {
          // console.log(res)
        }).catch((err) => {
          console.error(err);
        });
      }
    });

  }

  speechSynthesis(text) {
    if (this.played === false) {
      this.played = true;
    } else if (this.audio.ended === false) {
      return;
    }
    this.playText(text);
  }

  getToken(callback) {
    if (typeof (Storage) !== "undefined") {
      // console.log("has Storage function");
    } else {
      // console.warn("dosen't support storage");
      return;
    }
    // 检查本地token是否有效
    if (this.checkTokenIsExpired()) {
      // 网络请求Token
      fetch("https://api.lanchengiot.cn/api/baidu/oauth/2.0/token?grant_type=client_credentials&client_id=p9cAyHReZIbzsdoQQ3T7m9jT&client_secret=jjDGgzruPqtUlRo6tckib391MkFPTAWi", {
        method: 'GET',
      })
        .then((response) => response.json())
        .then(result => {
          sessionStorage.setItem('BDVoiceToken', result.access_token);

          let currentTime = Math.round(new Date().getTime() / 1000);
          sessionStorage.setItem('BDVoiceTokenExpireTime', currentTime + 2160000);
          callback(result.access_token, true);
        })
        .catch((error) => console.error(error))

    } else {
      sessionStorage.setItem('BDVoiceTokenExpireTime', null)
      sessionStorage.setItem('BDVoiceToken', null)

      fetch("https://api.lanchengiot.cn/api/baidu/oauth/2.0/token?grant_type=client_credentials&client_id=p9cAyHReZIbzsdoQQ3T7m9jT&client_secret=jjDGgzruPqtUlRo6tckib391MkFPTAWi", {
        method: 'GET',
      })
        .then((response) => response.json())
        .then(result => {
          sessionStorage.setItem('BDVoiceToken', result.access_token);

          let currentTime = Math.round(new Date().getTime() / 1000);
          sessionStorage.setItem('BDVoiceTokenExpireTime', currentTime + 2160000);
          callback(result.access_token, true);
        })
        .catch((error) => console.error(error))
    }
  }

  checkTokenIsExpired() {
    let currentTime = Math.round(new Date().getTime() / 1000)

    // sessionStorage.BDVoiceToken = 12;
    let expireTime = sessionStorage.getItem('BDVoiceTokenExpireTime');
    const BDVoiceToken = sessionStorage.getItem('BDVoiceToken');
    if (!BDVoiceToken || BDVoiceToken === "undefined") {
      return true;
    }
    // 2160000 25天

    if (expireTime < currentTime) {
      return true;
    }

    return false;
  }


}

// output f() speechSynthesis
export default SpeechPlayer;
